package io.coderyeah.basic.util;

import io.coderyeah.basic.jwt.JwtUtils;
import io.coderyeah.basic.jwt.LoginData;
import io.coderyeah.basic.jwt.Payload;
import io.coderyeah.basic.jwt.RsaUtils;
import io.coderyeah.user.domain.LoginInfo;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

/**
 * 获取登录用户
 */
public class LoginContext {
    public static LoginInfo getLoginInfo(HttpServletRequest req) {
        // 获取token
        final String token = req.getHeader("token");
        if (token != null) {
            // 获取公钥
            try {
                final PublicKey publicKey = RsaUtils.getPublicKey(LoginContext.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                // 解密
                final Payload<LoginData> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
                // 返回用户登录信息
                return payload.getLoginData().getLoginInfo();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
